package com.examination.mlib.utils;

import static android.graphics.Typeface.BOLD;
import static android.util.TypedValue.COMPLEX_UNIT_SP;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.examination.mlib.R;
import com.examination.mlib.baseold.AnswerRecommendDoctorEntity;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.AllStringConstants;
import com.google.gson.Gson;
import com.examination.mlib.baseold.AnswerDetailsListEntity;
import com.examination.mlib.baseold.AnswerResultEntity;
import com.examination.mlib.baseold.ClaimedRedEnvelopeEntity;
import com.examination.mlib.baseold.HomePopupEntity;
import com.examination.mlib.interfaceapi.NetWorkCallBack;
import com.examination.mlib.view.ProtocalDialog;
import com.examination.mlib.view.TrapezoidTextView;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.ScreenUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yilijk.base.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DialogUtils {
    private static String[] urls = new String[]{
            "yhzcjfwxy", "flsmjyszccs"
    };

    private static String[] titles = new String[]{
            "《慧医天下用户注册及服务协议》", "《隐私权政策》"
    };

    public static Dialog showAnswerInfoDialog(Activity activity, AnswerDetailsListEntity.DataItem dataItem) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View dialogView = inflater.inflate(R.layout.dialog_answer_info, null);
        Dialog dialog = new Dialog(activity, R.style.ShowDialog);
        dialog.setContentView(dialogView);
        TextView titleTv = dialogView.findViewById(R.id.tv_title);
        titleTv.setText(dataItem.getSubjectTitle());
        TextView answerTv = dialogView.findViewById(R.id.tv_answer);
//        ImageView ivFlag = dialogView.findViewById(R.id.iv_flag);
//        ivFlag.setImageResource(dataItem.isAnswerOption() ? R.drawable.icon_answer_true : R.drawable.icon_answer_fake);
        if (dataItem.isAnswerOption()) {
            answerTv.setText("答案：真的");
        } else {
            answerTv.setText("答案：假的");
        }
        ImageView ivFlagAnswer = dialogView.findViewById(R.id.iv_answer_flag);
        if (dataItem.isAnswerOption()) {
            ivFlagAnswer.setImageResource(R.drawable.ico_fake_answer);
            ivFlagAnswer.setScaleType(ImageView.ScaleType.FIT_START);
        } else {
            ivFlagAnswer.setScaleType(ImageView.ScaleType.FIT_END);
            ivFlagAnswer.setImageResource(R.drawable.ico_true_answer);
        }
        TextView yourAnswerTv = dialogView.findViewById(R.id.tv_your_answer);
        String filledOption = dataItem.getFilledOption();
        if (!TextUtils.isEmpty(filledOption)) {
            yourAnswerTv.setVisibility(View.VISIBLE);
            if ("true".equals(filledOption) && dataItem.isAnswerOption() || !"true".equals(filledOption) && !dataItem.isAnswerOption()) {
                yourAnswerTv.setText("您答对啦");
                yourAnswerTv.setTextColor(activity.getResources().getColor(R.color.text_blue));
            } else {
                yourAnswerTv.setText("您答错啦");
                yourAnswerTv.setTextColor(activity.getResources().getColor(R.color.text_red));
            }
        } else {
            yourAnswerTv.setVisibility(View.GONE);
        }
        TextView infoTv = dialogView.findViewById(R.id.tv_info);
//        infoTv.setText(String.format(activity.getString(R.string.space_start_2half), dataItem.getSubjectCommentary()));
        String answerInfo = "解答：" + dataItem.getSubjectCommentary();
        SpannableString spannableString = new SpannableString(answerInfo);
        ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(activity.getResources().getColor(R.color.text_gray));
        StyleSpan styleSpan = new StyleSpan(BOLD);
        spannableString.setSpan(colorSpan1, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(styleSpan, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        infoTv.setText(spannableString);

//        TextView errorTv = dialogView.findViewById(R.id.tv_error), correctTv = dialogView.findViewById(R.id.tv_correct);
//        String filledOption = dataItem.getFilledOption();
//        if (!TextUtils.isEmpty(filledOption)) {
//            if ("true".equals(filledOption)) {
//                correctTv.setText("已选真的");
//                errorTv.setText("假的");
//            } else {
//                correctTv.setText("真的");
//                errorTv.setText("已选假的");
//            }
//        } else {
//            correctTv.setText("真的");
//            errorTv.setText("假的");
//        }
        TextView correctRealTv = dialogView.findViewById(R.id.tv_correct_real),
                errorRealTv = dialogView.findViewById(R.id.tv_error_real);

        TrapezoidTextView correctRateTtv = dialogView.findViewById(R.id.ttv_correct_rate);
        TrapezoidTextView errorRateTtv = dialogView.findViewById(R.id.ttv_error_rate);
        correctRateTtv.setNoTrapezoid(false);
        correctRateTtv.setBackgroundResource(R.drawable.bg_left_line);
        errorRateTtv.setNoTrapezoid(false);
        errorRateTtv.setBackgroundResource(R.drawable.bg_right_line);
//        correctRateTtv.setText(dataItem.getCorrectRate() + "%");
//        errorRateTtv.setText(dataItem.getErrorRate() + "%");
        correctRateTtv.setText("");
        errorRateTtv.setText("");
        correctRealTv.setText(dataItem.getCorrectRate() + "%人选择");
        errorRealTv.setText(dataItem.getErrorRate() + "%人选择");
        if (dataItem.getErrorRate() == 0) {
            errorRateTtv.setVisibility(View.GONE);
            LinearLayout.LayoutParams correctParams = (LinearLayout.LayoutParams) correctRateTtv.getLayoutParams();
            correctParams.weight = 1;
            correctParams.rightMargin = 0;
            correctRateTtv.setLayoutParams(correctParams);
//            correctRateTtv.setText("100%");
            correctRateTtv.setNoTrapezoid(true);
            correctRateTtv.setBackgroundResource(R.drawable.bg_left_line_corner);
        } else if (dataItem.getCorrectRate() == 0) {
            LinearLayout.LayoutParams errorParams = (LinearLayout.LayoutParams) errorRateTtv.getLayoutParams();
            errorParams.weight = 1;
            errorParams.leftMargin = 0;
            errorRateTtv.setLayoutParams(errorParams);
//            errorRateTtv.setText("100%");
            errorRateTtv.setNoTrapezoid(true);
            errorRateTtv.setBackgroundResource(R.drawable.bg_right_line_corner);
            correctRateTtv.setVisibility(View.GONE);
        } else if (dataItem.getErrorRate() > 0 && dataItem.getErrorRate() < 13) {
            LinearLayout.LayoutParams errorParams = (LinearLayout.LayoutParams) errorRateTtv.getLayoutParams();
            errorParams.weight = 13;
            errorParams.leftMargin = -5;
            errorRateTtv.setLayoutParams(errorParams);
            LinearLayout.LayoutParams correctParams = (LinearLayout.LayoutParams) correctRateTtv.getLayoutParams();
            correctParams.weight = 87;
            correctParams.rightMargin = -5;
            correctRateTtv.setLayoutParams(correctParams);
        } else if (dataItem.getCorrectRate() > 0 && dataItem.getCorrectRate() < 13) {
            LinearLayout.LayoutParams errorParams = (LinearLayout.LayoutParams) errorRateTtv.getLayoutParams();
            errorParams.weight = 87;
            errorParams.leftMargin = -5;
            errorRateTtv.setLayoutParams(errorParams);
            LinearLayout.LayoutParams correctParams = (LinearLayout.LayoutParams) correctRateTtv.getLayoutParams();
            correctParams.weight = 13;
            correctParams.rightMargin = -5;
            correctRateTtv.setLayoutParams(correctParams);
        } else {
            LinearLayout.LayoutParams errorParams = (LinearLayout.LayoutParams) errorRateTtv.getLayoutParams();
            errorParams.weight = dataItem.getErrorRate();
            errorParams.leftMargin = -5;
            errorRateTtv.setLayoutParams(errorParams);
            LinearLayout.LayoutParams correctParams = (LinearLayout.LayoutParams) correctRateTtv.getLayoutParams();
            correctParams.weight = dataItem.getCorrectRate();
            correctParams.rightMargin = -5;
            correctRateTtv.setLayoutParams(correctParams);
        }


        View closeView = dialogView.findViewById(R.id.iv_close);
        ClickUtils.setFastOnClickListener(closeView, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog = null;
            }
        });

        dialog.setCancelable(true);
//        setDialogWindowAttr(dialog, activity);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM;
        lp.width = ScreenUtils.getScreenWidth();
        lp.height = (int) (ScreenUtils.getScreenHeight() * 0.6);
        dialog.getWindow().setAttributes(lp);
        dialog.show();
        return dialog;
    }

    /**
     * @param activity activity
     * @param url      弹窗图片url
     * @param listener listener
     */
    public static Dialog showHomeDialog(Activity activity, String url, final HomeActivityDialogListener listener) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View dialogView = inflater.inflate(R.layout.dialog_home_activity, null);
        Dialog dialog = new Dialog(activity, R.style.ShowDialog);
        dialog.setContentView(dialogView);

        ImageView activityIv = dialogView.findViewById(R.id.iv_activity),
                closeIv = dialogView.findViewById(R.id.iv_close);
        Glide.with(activity)
                .load(url)
                .error(R.drawable.icon_default_square)
                .into(activityIv);
        ClickUtils.setFastOnClickListener(closeIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.cancel();
                }
                if (listener != null) {
                    listener.onCancel();
                }
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (listener != null) {
                    listener.onDismiss();
                }
                dialog = null;
            }
        });
        ClickUtils.setFastOnClickListener(activityIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.cancel();
                }
                if (listener != null) {
                    listener.onActivityClick();
                }
            }
        });


        dialog.setCancelable(false);
//        setDialogWindowAttr(dialog, activity);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
//        lp.gravity = Gravity.CENTER;
        lp.width = (int) (ScreenUtils.getScreenWidth() * 0.9);
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
        dialog.show();
        return dialog;
    }

    public static Dialog showHomeAnswerDialog(Activity activity, String urlPath, HomePopupEntity.HomePagePopupAnswerVO answerVO, HomeAnswerListener listener) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View dialogView = inflater.inflate(R.layout.dialog_home_answer, null);
        Dialog dialog = new Dialog(activity, R.style.ShowDialog);
        dialog.setContentView(dialogView);
        View closeView = dialogView.findViewById(R.id.iv_close);
        ClickUtils.setFastOnClickListener(closeView, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        TextView titleTv = dialogView.findViewById(R.id.tv_title);
        titleTv.setText(answerVO.getSubjectTitle());
        titleTv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                titleTv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                if (titleTv.getLineCount() > 4) {
                    titleTv.setTextSize(COMPLEX_UNIT_SP, 14);
                }
            }
        });
        TextView timeTv = dialogView.findViewById(R.id.tv_time);
        SimpleDateFormat format = new SimpleDateFormat("MM月dd日");
        Date date = new Date(answerVO.getCurrentTime());
        String dateString = format.format(date);
        String dayString = getWeekOfDate(answerVO.getCurrentTime());
        timeTv.setText(dateString + " " + dayString);

        ClickUtils.setFastOnClickListener(dialogView.findViewById(R.id.iv_check_history), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onHistoryClick(answerVO);
                }
            }
        });
        ClickUtils.setFastOnClickListener(dialogView.findViewById(R.id.iv_real), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                answerResultFilled(activity, dialog, urlPath, answerVO.getPlatformActivitiesId(), answerVO.getPlatformActivitiesSubjectId(), true, listener);
            }
        });

        ClickUtils.setFastOnClickListener(dialogView.findViewById(R.id.iv_fake), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                answerResultFilled(activity, dialog, urlPath, answerVO.getPlatformActivitiesId(), answerVO.getPlatformActivitiesSubjectId(), false, listener);

            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (listener != null) {
                    listener.onDismiss();
                }
                dialog = null;
            }
        });

        dialog.setCancelable(false);
//        setDialogWindowAttr(dialog, activity);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
//        lp.gravity = Gravity.CENTER;
        lp.width = (int) (ScreenUtils.getScreenWidth() * 0.94);
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
        dialog.show();
        return dialog;
    }

    public static final int ENVELOPES_OVER = 1;
    public static final int ENVELOPES_ANSWER_WRONG = 0;

    public static Dialog showWrongAnswer(Activity activity, int type, WrongAnswerListener listener) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View dialogView = inflater.inflate(R.layout.dialog_wrong_answer, null);
        Dialog dialog = new Dialog(activity, R.style.ShowDialogScale);
        dialog.setContentView(dialogView);
        ImageView imageView = dialogView.findViewById(R.id.iv_wrong_answer);
        switch (type) {
            case ENVELOPES_ANSWER_WRONG: {
                imageView.setImageResource(R.drawable.bg_wrong_answer);
                break;
            }
            case ENVELOPES_OVER: {
                imageView.setImageResource(R.drawable.icon_envelopes_over);
                break;
            }
        }
        View knownView = dialogView.findViewById(R.id.view_known);
        ClickUtils.setFastOnClickListener(knownView, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (listener != null) {
                    listener.onDismiss();
                }
                dialog = null;
            }
        });
        dialog.setCancelable(false);
//        setDialogWindowAttr(dialog, activity);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = (int) (ScreenUtils.getScreenWidth() * 0.81);
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
        dialog.show();
        return dialog;
    }


    private static void getAnswerRecommendDoctor(Activity activity, Dialog redEnvelopesDialog, RedEnvelopesListener listener) {
        LoadingUtils.getLoadingUtils(activity).showLoading();

        HttpUtils.get(AllStringConstants.getAnswerRecommendDoctor, new HttpCallBack<AnswerRecommendDoctorEntity>() {
            @Override
            public void onSuccess(AnswerRecommendDoctorEntity entity, int i) {
                LoadingUtils.getLoadingUtils(activity).dismissLoading();
                if (redEnvelopesDialog != null) {
                    redEnvelopesDialog.dismiss();
                }
                if (listener != null) {
                    if (entity.getData() != null && "200".equals(entity.getStatus())) {
                        listener.useRmb(entity.getData());
                    }
                    listener.useRmb(null);
                }
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(activity).dismissLoading();
                if (redEnvelopesDialog != null) {
                    redEnvelopesDialog.dismiss();
                }
                if (listener != null) {
                    listener.useRmb(null);
                }
            }
        });
    }

    public static Dialog showRedEnvelopes(Activity activity, JSONObject jsonObject, String path, RedEnvelopesListener listener) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View dialogView = inflater.inflate(R.layout.dialog_red_envelopes, null);
        Dialog dialog = new Dialog(activity, R.style.ShowDialogScale);
        dialog.setContentView(dialogView);
        View closeView = dialogView.findViewById(R.id.iv_close);
        View useRmb = dialogView.findViewById(R.id.ll_use_rmb);
        ClickUtils.setFastOnClickListener(useRmb, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getAnswerRecommendDoctor(activity, dialog, listener);

//                if (redEnvelopesDialog != null) {
//                    redEnvelopesDialog.dismiss();
//                }
//                if (listener != null) {
//                    listener.useRmb();
//                }
            }
        });
        ClickUtils.setFastOnClickListener(closeView, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                if (listener != null) {
                    listener.onClose();
                }
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog = null;
            }
        });

        TextView countTv = dialogView.findViewById(R.id.tv_count);


        TextView titleTv = dialogView.findViewById(R.id.tv_title);
        ImageView cooperOpenIv = dialogView.findViewById(R.id.iv_copper_open);
        ImageView copperDanceIv = dialogView.findViewById(R.id.iv_copper_dance);
        AnimationDrawable danceAnim = (AnimationDrawable) copperDanceIv.getDrawable();
        View closeRedEnvelopesLl = dialogView.findViewById(R.id.ll_close_red_envelopes);
        View redBg = dialogView.findViewById(R.id.view_red_bg);
        ClickUtils.setFastOnClickListener(cooperOpenIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                cooperOpenIv.setVisibility(View.INVISIBLE);
                danceAnim.start();
                RequestParams params = null;
                try {
                    params = new RequestParams(jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                HttpUtils.get(path, params, new HttpCallBack<ClaimedRedEnvelopeEntity>() {
                    @Override
                    public void onSuccess(ClaimedRedEnvelopeEntity entity, int i) {
                        if (entity != null) {
                            if ("200".equals(entity.getStatus()) && entity.getData() != null) {

                                if (entity.getData().getHealthyCurrencyAmount() == 0) {
                                    cooperOpenIv.setVisibility(View.VISIBLE);
                                    danceAnim.stop();
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                    showWrongAnswer(activity, ENVELOPES_OVER, new WrongAnswerListener() {
                                        @Override
                                        public void onDismiss() {
                                            if (listener != null) {
                                                listener.onClose();
                                            }
                                        }
                                    });
                                    return;
                                }

                                String str = entity.getData().getHealthyCurrencyAmount() + "个健康币";
                                SpannableString spannableString = new SpannableString(str);
                                StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
                                AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(65, true);
                                spannableString.setSpan(styleSpan, 0, str.indexOf("个健康币"), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                spannableString.setSpan(sizeSpan, 0, str.indexOf("个健康币"), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                countTv.setText(spannableString);

                                copperDanceIv.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        danceAnim.stop();
                                        copperDanceIv.setVisibility(View.GONE);
                                        ObjectAnimator animatorA = ObjectAnimator.ofFloat(redBg, "alpha", 1f, 0f);

                                        ValueAnimator animatorH = ValueAnimator.ofInt(closeRedEnvelopesLl.getMeasuredHeight(), 0);
                                        animatorH.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                            @Override
                                            public void onAnimationUpdate(ValueAnimator animation) {
                                                ViewGroup.LayoutParams layoutParams = closeRedEnvelopesLl.getLayoutParams();
                                                layoutParams.height = (int) animation.getAnimatedValue();
                                                closeRedEnvelopesLl.setLayoutParams(layoutParams);

                                            }
                                        });

                                        AnimatorSet animatorSet = new AnimatorSet();
                                        animatorSet.play(animatorH).with(animatorA);
                                        animatorSet.setDuration(200);
                                        animatorSet.setInterpolator(new AccelerateInterpolator());
                                        animatorSet.addListener(new AnimatorListenerAdapter() {
                                            @Override
                                            public void onAnimationEnd(Animator animation) {
                                                super.onAnimationEnd(animation);
                                                closeRedEnvelopesLl.setVisibility(View.GONE);
                                                redBg.setVisibility(View.GONE);
                                                titleTv.setBackgroundResource(R.drawable.bg_red_arc_no_shade);
                                                titleTv.setText("慧医天下");
                                            }
                                        });
                                        animatorSet.start();
                                    }
                                }, 200);
                            } else {
                                if (!TextUtils.isEmpty(entity.getMessage())) {
                                    ToastUtils.showShort(entity.getMessage());
                                }

                                cooperOpenIv.setVisibility(View.VISIBLE);
                                danceAnim.stop();
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
                                if (listener != null) {
                                    listener.onClose();
                                }
                            }
                        } else {
                            cooperOpenIv.setVisibility(View.VISIBLE);
                            danceAnim.stop();
                        }
                    }


                    @Override
                    public void onFailure(String s, int i) {
                        cooperOpenIv.setVisibility(View.VISIBLE);
                        danceAnim.stop();
                    }
                });
            }
        });


        dialog.setCancelable(false);
        //        setDialogWindowAttr(dialog, activity);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = (int) (ScreenUtils.getScreenWidth() * 0.81);
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().

                setAttributes(lp);
        dialog.show();
        closeView.postDelayed(new

                                      Runnable() {
                                          @Override
                                          public void run() {
                                              closeView.setVisibility(View.VISIBLE);
                                          }
                                      }, 500);
        return dialog;
    }

    /**
     * 协议弹窗
     *
     * @param activity activity
     */
    public static Dialog showProtocalDialog(Activity activity, ProtocalDialogListener listener) {

        ProtocalDialog.Builder protocalDialogBuilder = new ProtocalDialog.Builder(activity);
//        protocalDialogBuilder.setMessage("");
//        protocalDialogBuilder.setTitle("医师注册协议");

        protocalDialogBuilder.setPositiveButton("同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                RequestParams jsonObject = new RequestParams();
                JSONArray jsonArray = new JSONArray();
                jsonArray.put("yhzcjfwxy");
                jsonArray.put("flsmjyszccs");
                jsonObject.put("documentNoList", jsonArray);
                LoadingUtils.getLoadingUtils(activity).showLoading();
                HttpUtils.get(AllStringConstants.preserveAgreement, jsonObject, new HttpCallBack<String>() {
                    @Override
                    public void onSuccess(String resultMsg, int code) {
                        LoadingUtils.getLoadingUtils(activity).dismissLoading();
                        if (code == 200) {
                            try {
                                JSONObject jsonObject1 = new JSONObject(resultMsg);
                                boolean data = jsonObject1.getBoolean("data");
                                if (data) {
                                    dialog.dismiss();
                                    if (listener != null) {
                                        listener.onAgreement();
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(String s, int i) {
                        LoadingUtils.getLoadingUtils(activity).dismissLoading();
                    }
                });
            }
        });
        protocalDialogBuilder.setNegativeButton("不同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //不同意退出登录
                boolean b = SharedPreferencesUtils.getInstance().removeAll();
                if (b) {
                    ARouter.getInstance().build(ARouterConstants.CenterActivity).navigation();
                    dialog.dismiss();
                    if (activity != null && !activity.isFinishing()) {
                        activity.finish();
                    }
                }
            }
        });

        final SpannableStringBuilder style = new SpannableStringBuilder();

        final String content = "感谢您对慧医天下互联网医疗平台的信任！为了更好地保护您的个人信息安全和合法权益，请您务必仔细阅读并充分理解我们最新的《慧医天下用户注册及服务协议》和《隐私权政策》和《医师多机构备案劳务协议》。我们将严格按照您同意的各项条使用和保护您的个人信息，并为您提供相关服务。\n" +
                "详细信息请阅读完整版《慧医天下用户注册及服务协议》和《隐私权政策》。";

        //设置文字
        style.append(content);


        int a_l = content.indexOf("《慧医天下用户注册及服务协议》");
        int a_L = a_l + "《慧医天下用户注册及服务协议》".length();

        int a_l2 = content.lastIndexOf("《慧医天下用户注册及服务协议》");
        int a_L2 = a_l2 + "《慧医天下用户注册及服务协议》".length();


        int b_l = content.indexOf("《隐私权政策》");
        int b_L = b_l + "《隐私权政策》".length();

        int b_l2 = content.lastIndexOf("《隐私权政策》");
        int b_L2 = b_l2 + "《隐私权政策》".length();

//        int c_l = content.indexOf("《医师多机构备案劳务协议》");
//        int c_L = c_l + "《医师多机构备案劳务协议》".length();
//
//        int c_l2 = content.lastIndexOf("《医师多机构备案劳务协议》");
//        int c_L2 = c_l2 + "《医师多机构备案劳务协议》".length();

        style.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                toWebAgreement(1);
            }
        }, a_l, a_L, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                toWebAgreement(1);
            }
        }, a_l2, a_L2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        style.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                toWebAgreement(2);
            }
        }, b_l, b_L, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                toWebAgreement(2);
            }
        }, b_l2, b_L2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


        style.setSpan(new StyleSpan(Typeface.BOLD), a_l, a_L, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new StyleSpan(Typeface.BOLD), a_l2, a_L2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new StyleSpan(Typeface.BOLD), b_l, b_L, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new StyleSpan(Typeface.BOLD), b_l2, b_L2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置部分文字颜色
        style.setSpan(new ForegroundColorSpan(Color.parseColor("#1A1A1A")), a_l, a_L, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new ForegroundColorSpan(Color.parseColor("#1A1A1A")), a_l2, a_L2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        style.setSpan(new ForegroundColorSpan(Color.parseColor("#1A1A1A")), b_l, b_L, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new ForegroundColorSpan(Color.parseColor("#1A1A1A")), b_l2, b_L2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        protocalDialogBuilder.setMessage(style);

        Dialog dialog = protocalDialogBuilder.create();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog = null;
            }
        });
        dialog.setCancelable(false);
        dialog.show();
        return dialog;
    }

    private static void toWebAgreement(int i) {

        String url = "https://www.yilijk.com" + "/document/index.html?id=" + urls[i - 1];
        ALog.i("toWebAgreement", "toWebAgreement: " + url);
        ARouter.getInstance().build(ARouterConstants.MineWebviewActivity)
                .withString("title", titles[i - 1])
                .withString("url", url)
                .withBoolean("ishtml", false)
                .navigation();

    }

    /**
     * HomeUrl.answerResultFilled
     *
     * @param activity
     * @param answer
     */
    private static void answerResultFilled(Activity activity, Dialog dialog, String urlPath, String platformActivitiesId, String platformActivitiesSubjectId, boolean answer, HomeAnswerListener listener) {

        RequestParams jsonObject = new RequestParams();
        jsonObject.put("platformActivitiesId", platformActivitiesId);
        jsonObject.put("subjectId", platformActivitiesSubjectId);
        jsonObject.put("filledOption", answer);
        LoadingUtils.getLoadingUtils(activity).showLoading();
        HttpUtils.get(urlPath, jsonObject, new HttpCallBack<AnswerResultEntity>() {
            @Override
            public void onSuccess(AnswerResultEntity entity, int i) {
                LoadingUtils.getLoadingUtils(activity).dismissLoading();
                if (entity != null) {
                    if ("200".equals(entity.getStatus()) && entity.getData() != null) {
                        if (entity.getData().isFilledResult()) {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                            if (listener != null) {
                                listener.onBingo(entity.getData());
                            }
                        } else {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                            if (listener != null) {
                                listener.onWrong();
                            }
                        }
                    } else {
                        if (!TextUtils.isEmpty(entity.getMessage())) {
                            ToastUtils.showShort(entity.getMessage());
                        }
                    }
                }
            }

            @Override
            public void onFailure(String s, int i) {

                LoadingUtils.getLoadingUtils(activity).dismissLoading();
            }
        });
    }


    public static String getWeekOfDate(long time) {

        Date date = new Date(time);
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;

        return weekDays[w];
    }

    private static void setDialogWindowAttr(Dialog dlg, Context ctx) {
        Window window = dlg.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
//        lp.width = WindowManager.LayoutParams.MATCH_PARENT;//宽高可设置具体大小
//        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.width = (int) (ScreenUtils.getScreenWidth() * 0.9);
//        lp.height = (int) (ScreenUtils.getScreenHeight(ctx) * 0.75);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dlg.getWindow().setAttributes(lp);
    }

    public interface HomeActivityDialogListener {
        void onCancel();

        void onActivityClick();

        void onDismiss();
    }

    public interface RedEnvelopesListener {
        void onClose();

        void useRmb(AnswerRecommendDoctorEntity.Data data);
    }

    public interface WrongAnswerListener {
        void onDismiss();
    }

    public interface ProtocalDialogListener {
        void onAgreement();
    }

    public interface HomeAnswerListener {
        void onHistoryClick(HomePopupEntity.HomePagePopupAnswerVO answerVO);

        void onBingo(AnswerResultEntity.Data data);

        void onWrong();

        void onDismiss();

    }

}
